/**
 * 发布订阅
 */
class PubSub {
	// 存储订阅者和其对应的回调函数
	private subscribers: Record<string, Array<(...args: any[]) => void>> = {};

	/**
	 * 添加订阅者
	 * @param event 事件名称
	 * @param callback 回调
	 */
	public subscribe(event: string, callback: (...args: any[]) => void): void {
		if (!this.subscribers[event]) {
			this.subscribers[event] = [];
		}
		this.subscribers[event].push(callback);
	}

	/**
	 * 发布事件
	 * @param event 事件名称
	 * @param data 数据
	 */
	public publish(event: string, data: any, oldData: any): void {
		if (this.subscribers[event]) {
			this.subscribers[event].forEach((callback) => {
				callback(data, oldData);
			});
		}
	}

	/**
	 * 移出
	 * @param event
	 */
	public remove(event: string) {
		delete this.subscribers[event];
	}
}

export { PubSub };
